/**
 * 原型图优化主执行脚本
 * 按照TASK文档执行完整的优化流程
 */

const fs = require('fs');
const path = require('path');
const SVGOptimizer = require('./svg-optimizer');

// 配置路径
const CONFIG = {
  inputDir: path.resolve(__dirname, '../../screens/svg'),
  outputDir: path.resolve(__dirname, '../../screens/prototype'),
  designStandardsPath: path.resolve(__dirname, './design-standards.json'),
  logDir: path.resolve(__dirname, './logs'),
  reportDir: path.resolve(__dirname, './reports')
};

class PrototypeOptimizer {
  constructor() {
    this.designStandards = null;
    this.optimizer = null;
    this.startTime = null;
    this.logs = [];
  }

  /**
   * 主执行函数
   */
  async run() {
    try {
      this.startTime = new Date();
      this.log('开始原型图优化流程', 'info');
      
      // TASK-1: 环境准备和工具配置
      await this.task1_setupEnvironment();
      
      // TASK-2: 文件分析和分类
      const analysisResult = await this.task2_analyzeFiles();
      
      // TASK-3: 设计规范标准化
      await this.task3_standardizeDesign();
      
      // TASK-4: 批量SVG优化处理
      const optimizationResult = await this.task4_optimizeSVGs();
      
      // TASK-5: 质量验证和测试
      const validationResult = await this.task5_validateQuality(optimizationResult);
      
      // TASK-6: 文件迁移和组织
      await this.task6_organizeFiles(optimizationResult);
      
      // TASK-7: 文档更新和总结
      await this.task7_updateDocumentation({
        analysis: analysisResult,
        optimization: optimizationResult,
        validation: validationResult
      });
      
      this.log('原型图优化流程完成', 'success');
      
    } catch (error) {
      this.log(`优化流程失败: ${error.message}`, 'error');
      throw error;
    }
  }

  /**
   * TASK-1: 环境准备和工具配置
   */
  async task1_setupEnvironment() {
    this.log('TASK-1: 环境准备和工具配置', 'task');
    
    // 创建必要的目录
    const dirs = [CONFIG.outputDir, CONFIG.logDir, CONFIG.reportDir];
    dirs.forEach(dir => {
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
        this.log(`创建目录: ${dir}`, 'info');
      }
    });
    
    // 加载设计规范
    if (!fs.existsSync(CONFIG.designStandardsPath)) {
      throw new Error('设计规范文件不存在');
    }
    
    this.designStandards = JSON.parse(fs.readFileSync(CONFIG.designStandardsPath, 'utf8'));
    this.optimizer = new SVGOptimizer(this.designStandards);
    
    this.log('环境准备完成', 'success');
  }

  /**
   * TASK-2: 文件分析和分类
   */
  async task2_analyzeFiles() {
    this.log('TASK-2: 文件分析和分类', 'task');
    
    if (!fs.existsSync(CONFIG.inputDir)) {
      throw new Error(`输入目录不存在: ${CONFIG.inputDir}`);
    }
    
    const files = fs.readdirSync(CONFIG.inputDir).filter(file => file.endsWith('.svg'));
    this.log(`发现 ${files.length} 个SVG文件`, 'info');
    
    const analysis = {
      totalFiles: files.length,
      files: [],
      categories: {},
      totalSize: 0
    };
    
    // 分析每个文件
    files.forEach(file => {
      const filePath = path.join(CONFIG.inputDir, file);
      const stats = fs.statSync(filePath);
      const content = fs.readFileSync(filePath, 'utf8');
      
      // 基本信息
      const fileInfo = {
        name: file,
        size: stats.size,
        lastModified: stats.mtime,
        category: this.categorizeFile(file),
        complexity: this.analyzeComplexity(content)
      };
      
      analysis.files.push(fileInfo);
      analysis.totalSize += stats.size;
      
      // 分类统计
      if (!analysis.categories[fileInfo.category]) {
        analysis.categories[fileInfo.category] = 0;
      }
      analysis.categories[fileInfo.category]++;
    });
    
    // 保存分析结果
    const analysisPath = path.join(CONFIG.reportDir, 'file-analysis.json');
    fs.writeFileSync(analysisPath, JSON.stringify(analysis, null, 2));
    
    this.log(`文件分析完成，结果保存到: ${analysisPath}`, 'success');
    return analysis;
  }

  /**
   * 文件分类
   */
  categorizeFile(fileName) {
    const name = fileName.toLowerCase();
    
    if (name.includes('welcome') || name.includes('intro')) return 'welcome';
    if (name.includes('login') || name.includes('auth')) return 'auth';
    if (name.includes('wallet') || name.includes('asset')) return 'wallet';
    if (name.includes('trade') || name.includes('market')) return 'trading';
    if (name.includes('profile') || name.includes('user')) return 'profile';
    if (name.includes('setting') || name.includes('config')) return 'settings';
    
    return 'other';
  }

  /**
   * 分析文件复杂度
   */
  analyzeComplexity(content) {
    const elementCount = (content.match(/<[^/][^>]*>/g) || []).length;
    const pathCount = (content.match(/<path/g) || []).length;
    const textCount = (content.match(/<text/g) || []).length;
    
    let complexity = 'simple';
    if (elementCount > 50 || pathCount > 10) complexity = 'medium';
    if (elementCount > 100 || pathCount > 20) complexity = 'complex';
    
    return {
      level: complexity,
      elementCount,
      pathCount,
      textCount
    };
  }

  /**
   * TASK-3: 设计规范标准化
   */
  async task3_standardizeDesign() {
    this.log('TASK-3: 设计规范标准化', 'task');
    
    // 验证设计规范的完整性
    const requiredSections = ['canvas', 'colors', 'typography', 'layout', 'components'];
    const missingSections = requiredSections.filter(section => !this.designStandards[section]);
    
    if (missingSections.length > 0) {
      throw new Error(`设计规范缺少必要部分: ${missingSections.join(', ')}`);
    }
    
    // 生成标准化配置报告
    const standardsReport = {
      version: this.designStandards.metadata?.version || '1.0.0',
      sections: requiredSections.map(section => ({
        name: section,
        configured: !!this.designStandards[section],
        itemCount: Object.keys(this.designStandards[section] || {}).length
      })),
      colorPalette: Object.keys(this.designStandards.colors || {}),
      fontSizes: Object.keys(this.designStandards.typography?.sizes || {}),
      components: Object.keys(this.designStandards.components || {})
    };
    
    const reportPath = path.join(CONFIG.reportDir, 'design-standards-report.json');
    fs.writeFileSync(reportPath, JSON.stringify(standardsReport, null, 2));
    
    this.log('设计规范标准化完成', 'success');
  }

  /**
   * TASK-4: 批量SVG优化处理
   */
  async task4_optimizeSVGs() {
    this.log('TASK-4: 批量SVG优化处理', 'task');
    
    const results = await this.optimizer.processBatch(
      CONFIG.inputDir,
      CONFIG.outputDir,
      (current, total, fileName, success) => {
        const status = success ? '✓' : '✗';
        this.log(`[${current}/${total}] ${status} ${fileName}`, 'progress');
      }
    );
    
    // 统计结果
    const stats = {
      total: results.length,
      successful: results.filter(r => r.success).length,
      failed: results.filter(r => !r.success).length,
      totalSizeReduction: 0,
      averageCompressionRatio: 0
    };
    
    const successfulResults = results.filter(r => r.success && r.metrics);
    if (successfulResults.length > 0) {
      stats.totalSizeReduction = successfulResults.reduce((sum, r) => sum + r.metrics.sizeReduction, 0);
      const avgCompression = successfulResults.reduce((sum, r) => sum + parseFloat(r.metrics.compressionRatio), 0) / successfulResults.length;
      stats.averageCompressionRatio = `${avgCompression.toFixed(2)}%`;
    }
    
    // 保存优化结果
    const optimizationReport = {
      timestamp: new Date().toISOString(),
      statistics: stats,
      results: results
    };
    
    const reportPath = path.join(CONFIG.reportDir, 'optimization-report.json');
    fs.writeFileSync(reportPath, JSON.stringify(optimizationReport, null, 2));
    
    this.log(`优化完成: ${stats.successful}/${stats.total} 成功`, 'success');
    return optimizationReport;
  }

  /**
   * TASK-5: 质量验证和测试
   */
  async task5_validateQuality(optimizationResult) {
    this.log('TASK-5: 质量验证和测试', 'task');
    
    const validationResults = {
      timestamp: new Date().toISOString(),
      tests: [],
      summary: {
        totalTests: 0,
        passed: 0,
        failed: 0,
        warnings: 0
      }
    };
    
    const successfulFiles = optimizationResult.results.filter(r => r.success);
    
    for (const result of successfulFiles) {
      const filePath = path.join(CONFIG.outputDir, result.originalFile);
      
      if (fs.existsSync(filePath)) {
        const content = fs.readFileSync(filePath, 'utf8');
        const fileValidation = this.validateSVGFile(content, result.originalFile);
        validationResults.tests.push(fileValidation);
        
        validationResults.summary.totalTests++;
        if (fileValidation.passed) {
          validationResults.summary.passed++;
        } else {
          validationResults.summary.failed++;
        }
        validationResults.summary.warnings += fileValidation.warnings.length;
      }
    }
    
    // 保存验证结果
    const reportPath = path.join(CONFIG.reportDir, 'validation-report.json');
    fs.writeFileSync(reportPath, JSON.stringify(validationResults, null, 2));
    
    this.log(`质量验证完成: ${validationResults.summary.passed}/${validationResults.summary.totalTests} 通过`, 'success');
    return validationResults;
  }

  /**
   * 验证单个SVG文件
   */
  validateSVGFile(content, fileName) {
    const validation = {
      fileName,
      passed: true,
      errors: [],
      warnings: []
    };
    
    try {
      // 基本SVG语法验证
      if (!content.includes('<svg')) {
        validation.errors.push('Missing SVG root element');
        validation.passed = false;
      }
      
      // 检查是否有未闭合的标签
      const openTags = (content.match(/<[^/][^>]*[^/]>/g) || []).length;
      const closeTags = (content.match(/<\/[^>]*>/g) || []).length;
      const selfClosingTags = (content.match(/<[^>]*\/>/g) || []).length;
      
      if (openTags !== closeTags + selfClosingTags) {
        validation.warnings.push('Potential unclosed tags detected');
      }
      
      // 检查是否符合设计规范
      const canvas = this.designStandards.canvas;
      if (!content.includes(`width="${canvas.width}"`)) {
        validation.warnings.push('Canvas width may not match standards');
      }
      
      if (!content.includes(`height="${canvas.height}"`)) {
        validation.warnings.push('Canvas height may not match standards');
      }
      
      // 检查是否包含标准颜色
      const standardColors = Object.values(this.designStandards.colors).filter(c => typeof c === 'string');
      const hasStandardColors = standardColors.some(color => content.includes(color));
      if (!hasStandardColors) {
        validation.warnings.push('No standard colors detected');
      }
      
    } catch (error) {
      validation.errors.push(`Validation error: ${error.message}`);
      validation.passed = false;
    }
    
    return validation;
  }

  /**
   * TASK-6: 文件迁移和组织
   */
  async task6_organizeFiles(optimizationResult) {
    this.log('TASK-6: 文件迁移和组织', 'task');
    
    // 创建文件映射表
    const fileMapping = {
      timestamp: new Date().toISOString(),
      sourceDir: CONFIG.inputDir,
      targetDir: CONFIG.outputDir,
      mappings: []
    };
    
    optimizationResult.results.forEach(result => {
      if (result.success) {
        fileMapping.mappings.push({
          originalFile: result.originalFile,
          originalPath: path.join(CONFIG.inputDir, result.originalFile),
          optimizedPath: path.join(CONFIG.outputDir, result.originalFile),
          status: 'migrated',
          changes: result.changes?.length || 0
        });
      } else {
        fileMapping.mappings.push({
          originalFile: result.originalFile,
          originalPath: path.join(CONFIG.inputDir, result.originalFile),
          status: 'failed',
          error: result.error
        });
      }
    });
    
    // 保存文件映射
    const mappingPath = path.join(CONFIG.reportDir, 'file-mapping.json');
    fs.writeFileSync(mappingPath, JSON.stringify(fileMapping, null, 2));
    
    this.log('文件迁移和组织完成', 'success');
  }

  /**
   * TASK-7: 文档更新和总结
   */
  async task7_updateDocumentation(results) {
    this.log('TASK-7: 文档更新和总结', 'task');
    
    const endTime = new Date();
    const duration = endTime - this.startTime;
    
    // 生成总结报告
    const summary = {
      project: 'HRC原型图优化',
      timestamp: endTime.toISOString(),
      duration: `${Math.round(duration / 1000)}秒`,
      overview: {
        totalFiles: results.analysis.totalFiles,
        successfulOptimizations: results.optimization.statistics.successful,
        failedOptimizations: results.optimization.statistics.failed,
        validationPassed: results.validation.summary.passed,
        validationFailed: results.validation.summary.failed
      },
      performance: {
        totalSizeReduction: results.optimization.statistics.totalSizeReduction,
        averageCompressionRatio: results.optimization.statistics.averageCompressionRatio
      },
      qualityMetrics: {
        validationPassRate: `${((results.validation.summary.passed / results.validation.summary.totalTests) * 100).toFixed(1)}%`,
        totalWarnings: results.validation.summary.warnings
      },
      logs: this.logs
    };
    
    // 保存总结报告
    const summaryPath = path.join(CONFIG.reportDir, 'optimization-summary.json');
    fs.writeFileSync(summaryPath, JSON.stringify(summary, null, 2));
    
    // 生成Markdown报告
    const markdownReport = this.generateMarkdownReport(summary);
    const markdownPath = path.join(CONFIG.reportDir, 'optimization-summary.md');
    fs.writeFileSync(markdownPath, markdownReport);
    
    this.log(`文档更新完成，报告保存到: ${summaryPath}`, 'success');
  }

  /**
   * 生成Markdown报告
   */
  generateMarkdownReport(summary) {
    return `# HRC原型图优化总结报告

## 项目概览

- **项目名称**: ${summary.project}
- **完成时间**: ${summary.timestamp}
- **执行时长**: ${summary.duration}

## 处理结果

### 文件处理统计
- 总文件数: ${summary.overview.totalFiles}
- 成功优化: ${summary.overview.successfulOptimizations}
- 优化失败: ${summary.overview.failedOptimizations}
- 成功率: ${((summary.overview.successfulOptimizations / summary.overview.totalFiles) * 100).toFixed(1)}%

### 质量验证结果
- 验证通过: ${summary.overview.validationPassed}
- 验证失败: ${summary.overview.validationFailed}
- 通过率: ${summary.qualityMetrics.validationPassRate}
- 警告数量: ${summary.qualityMetrics.totalWarnings}

### 性能优化效果
- 总体积减少: ${summary.performance.totalSizeReduction} 字节
- 平均压缩率: ${summary.performance.averageCompressionRatio}

## 优化内容

1. **设计规范统一**: 应用新的色彩系统、字体规范和布局标准
2. **代码优化**: 改进SVG代码结构，提升渲染性能
3. **视觉效果优化**: 统一阴影效果、圆角等视觉元素
4. **兼容性改进**: 确保跨浏览器兼容性

## 文件位置

- **原始文件**: \`screens/svg/\`
- **优化后文件**: \`screens/prototype/\`
- **详细报告**: \`docs/prototype-optimization/reports/\`

## 后续维护

1. 定期检查优化后的文件是否符合最新设计规范
2. 如需添加新的原型图，请参考现有的设计标准
3. 如发现问题，请查看详细的验证报告进行排查

---

*报告生成时间: ${new Date().toLocaleString()}*
`;
  }

  /**
   * 日志记录
   */
  log(message, type = 'info') {
    const timestamp = new Date().toISOString();
    const logEntry = {
      timestamp,
      type,
      message
    };
    
    this.logs.push(logEntry);
    
    // 控制台输出
    const colors = {
      info: '\x1b[36m',    // 青色
      success: '\x1b[32m', // 绿色
      warning: '\x1b[33m', // 黄色
      error: '\x1b[31m',   // 红色
      task: '\x1b[35m',    // 紫色
      progress: '\x1b[90m' // 灰色
    };
    
    const color = colors[type] || '\x1b[0m';
    const reset = '\x1b[0m';
    
    console.log(`${color}[${type.toUpperCase()}] ${message}${reset}`);
  }
}

// 主执行函数
async function main() {
  const optimizer = new PrototypeOptimizer();
  
  try {
    await optimizer.run();
    console.log('\n🎉 原型图优化完成！');
    console.log(`📁 优化后的文件位置: ${CONFIG.outputDir}`);
    console.log(`📊 详细报告位置: ${CONFIG.reportDir}`);
  } catch (error) {
    console.error('\n❌ 优化过程中发生错误:');
    console.error(error.message);
    process.exit(1);
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}

module.exports = PrototypeOptimizer;